//
//  HttpDatas.swift
//  News
//
//  Created by Mac on 2025/5/9.
//

import Foundation
import Alamofire

private let httpShareInstance = HttpDatas()

//数据请求方法
enum MethodType{
    case get
    case post
}

class HttpDatas: NSObject{
    
    //单例
    class var sharedInstance: HttpDatas{
        return httpShareInstance
    }
    
}


extension HttpDatas{
    /// 网络请求通用版
    ///
    /// - Parameters:
    ///     - type: 数据请求方式 get/post
    ///     - URLString: 请求数据的路径
    ///     - parameters: 请求数据需要的参数
    ///     - finishCallBack: 请求成功后通过这个block把数据回调
    func requestDatas(_ type:MethodType, URLString:String, parameters:[String:Any]?, finishCallBack:@escaping(_ response:Any)->()){
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        Alamofire.request(URLString, method:method, parameters:parameters, encoding:URLEncoding.default, headers:nil).responseJSON{
            (responseJson) in
         
            guard responseJson.result.value != nil else{
                print(responseJson.result.error)
                return
            }
            
            guard responseJson.result.isSuccess else{
                return
            }
            
            if let value = responseJson.result.value{
                finishCallBack(value)
            }
        }
        
    }
}
